using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using SimpleJson;
using Mars.Client;
using System.Threading;
using WebSocket4Net;

public class LoginGUIBestHttp : MonoBehaviour {
	
	public static string userName = "gakaki";
	public static string channel = "1";

	public static JsonObject users = null;
	
	public static MarsClient mc = null;
	
	public Texture2D pomelo;
	public GUISkin pomeloSkin; 
	public GUIStyle pomeloStyle;
	
	
	public readonly static Queue<Action> ExecuteOnMainThread = new Queue<Action>();
	
	void Start() 
	{	
		pomelo = (Texture2D)Resources.Load("pomelo");
		pomeloStyle.normal.textColor = Color.black;


		string host 	= Config.host;
		int port 		= Config.port;
		
		mc 				= new MarsClient(host, port);
		mc.init ();

	}
	
	//When quit, release resource
	void Update(){
		if(Input.GetKey(KeyCode.Escape)) {
			if (mc != null) {
				mc.disconnect();
			}
			Application.Quit();
		}
		
		// dispatch stuff on main thread
		while (ExecuteOnMainThread.Count > 0)
		{
			ExecuteOnMainThread.Dequeue().Invoke();
		}
	}
	
	//When quit, release resource
	void OnApplicationQuit(){
		if (mc != null) {
			mc.disconnect();
		}
	}
	
	void Login() {

		Debug.Log(" start login process !");

		mc.connect(null, (data)=>{

			Debug.Log(" in Connect ");

			JsonObject msg = new JsonObject();
			msg["uid"] = userName;
			mc.request("gate.gateHandler.queryEntry", msg, OnQuery);
		});
	}
	
	void OnQuery(JsonObject result){
		if(Convert.ToInt32(result["code"]) == 200){
			mc.disconnect();


			string host = (string)result["host"];
			int port = Convert.ToInt32(result["port"]);

			Debug.Log(" in OnQuery reconnect it " + host + "  " + port );
			mc = new MarsClient(host, port);
			mc.webSocket.OnOpen += onOpenOnce;
			mc.init();

			Debug.Log( " is mc open " + mc.webSocket.IsOpen.ToString());
		}
	}
	void onOpenOnce(BestHTTP.WebSocket.WebSocket ws)
	{
		Debug.Log ("-websocket is opened " +  ws.IsOpen );
		mc.connect(null, (data)=>{
			Entry();
		});	
	}

	//Entry chat application.
	void Entry(){
		JsonObject userMessage = new JsonObject();
		userMessage.Add("username", userName);
		userMessage.Add("rid", channel);
		Debug.Log ( " entry enter  ");
		if (mc != null) {
			mc.request("connector.entryHandler.enter", userMessage, (data)=>{

				users = data;

				Debug.Log( "  connector.entryHandler.enter callback ing " );
				ExecuteOnMainThread.Enqueue(() => {  
					StartCoroutine("LoadLevel"); 
				} );
				
			});
		}
	}
	
	void LoadLevel(){
//		Application.LoadLevel(Application.loadedLevel + 1);
		Application.LoadLevel( "chatBestHttp" );
	}
	
	void OnGUI(){
		GUI.skin = pomeloSkin;
		GUI.color = Color.yellow;
		GUI.enabled = true;	
		GUI.Label(new Rect(160, 50, pomelo.width, pomelo.height), pomelo);
		
		GUI.Label(new Rect(75, 350, 50, 20), "name:", pomeloStyle);
		userName = GUI.TextField(new Rect(125, 350, 90, 20), userName);
		GUI.Label(new Rect(225, 350, 55, 20), "channel:", pomeloStyle);
		channel = GUI.TextField(new Rect(280, 350, 100, 20), channel);
		
		if (GUI.Button(new Rect(410, 350, 70, 20), "OK")) {
			Debug.Log( " is mc null " +  ( mc == null ? true : false ));
			if (mc != null) {
				Login();
			}
		}	
	}
 }